/*
 * GET home page.
 */

exports.homeData = function(req , res){
	var async = require('async');
	var mysql = require('mysql');
	var client = mysql.createConnection(myDb);
	var list = req.body.list?req.body.list*1:0;
	var limit =  list>0 ? " limit "+(list*5+1-5)+", 5":" limit 1";
	client.connect();
	client.query("use " + myDb.DbName);
		async.waterfall([
			function(callback){
				//热门群
				if(list==0){
					client.query("SELECT COUNT( * ) AS num, a.gid, b.uName AS groupName, b.gType, b.groupNote, b.headPath FROM  `360_group_member` AS a JOIN  `360_group` AS b WHERE a.gid = b.gid GROUP BY gid LIMIT 6",
						function selectCb(err, results, fields){
							if(results.length)
								callback(null,results);
							else
								callback(null,[]);
						}
					)
				}
				else
					callback(null,[]);
			},
			function(a1,callback){
				if(list==0){
					client.query("SELECT nickName,id,headPath FROM  `360_member` ORDER BY  `id` DESC limit 10",
						function selectCb(err, results, fields){
							if(results.length)
								callback(null,results,a1);
							else
								callback(null,[],a1);
						}
					)
				}
				else
					callback(null,[],a1);
			},
			function(b1,b2,callback){
				client.query("SELECT `id` as sid,  `ImgPath` ,  `showNote` ,  `likeNumber` ,  `dislikeNumber`  FROM  `360_show`  WHERE 1  GROUP BY  `likeNumber`  ORDER BY  `likeNumber` DESC  "+limit,
					function selectCb(err, results, fields){
						console.log("SELECT `ImgPath` ,  `showNote` ,  `likeNumber` ,  `dislikeNumber`  FROM  `360_show`  WHERE 1  GROUP BY  `likeNumber`  ORDER BY  `likeNumber` DESC  "+limit);
						var data = {};
						data.GroupData = b2;
						data.NewMemberData = b1;
						if(results.length){
							data.showData = results;
							
							
							for(i in results){
								console.log(i);
							}
							
							
							res.send(JSON.stringify(data));
						}
						else{
							data.showData = [];
							res.send(JSON.stringify(data));
						}
					}
				)

				
			}],
			function (err, result) {
				
				return;
				
			}
		)
}




 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

exports.index = function(req , res){
	var mysql = require('mysql');
	var TEST_DATABASE = 'weibang';
	var TEST_TABLE = '360_member';
	var client = mysql.createConnection({
		user: 'root',
		password: '',
	});
	client.connect();
	client.query("use " + TEST_DATABASE);
	client.query(
		'SELECT * FROM '+TEST_TABLE,  
		function selectCb(err, results, fields){
			if (err)
			  throw err;
			if(results){
				for(var i = 0; i < results.length; i++){
					//console.log("%d\t%s\t%s", results[i].id, results[i].nickName, results[i].area);
					
				}
			}
			client.end();
		}
	);

	res.end(key);	
};

//加密
exports.aes = function(req, res){
	var aes = {
		'encode' : function(data, secretKey){
			var cipher = crypto.createCipher('aes-128-cbc',secretKey);  
			return cipher.update(data,'utf8','base64') + cipher.final('base64');  
		},
		'decode' : function(data, secretKey){
			var cipher = crypto.createDecipher('aes-128-cbc',secretKey);
			var code = cipher.update(data,'base64','utf8') + cipher.final('utf8');
				if(code)
					return code;
				else
					return "";
		}
	}
		if(req.param('id')){
			var code = aes.encode("1447570637"+"|"+"13333333333"+"|"+req.param('id')+"|"+"/od/jjj.png",key);
			res.end(code);
		}
		else{
			var code = aes.encode('aaaaa',key);
			if(code != "")
				res.end(code);
			else
				res.end("123");
		}
}


exports.socket = function(req, res){
	var express = require('express'),
		app = express(),
		server = require('http').createServer(app),
		io = require('socket.io').listen(server),
		users=[];//保存所有在线用户的昵称
	app.use('/', express.static(__dirname + '/www'));
	server.listen(80);
	//socket部分
	io.on('connection', function(socket) {
		//昵称设置
		socket.on('login', function(nickname) {
			if (users.indexOf(nickname) > -1) {
				socket.emit('nickExisted');
			} else {
				socket.userIndex = users.length;
				socket.nickname = nickname;
				users.push(nickname);
				socket.emit('loginSuccess');
				io.sockets.emit('system', nickname); //向所有连接到服务器的客户端发送当前登陆用户的昵称 
			};
		});
	});
	res.render('socket', {});
}



//表单提交测试
exports.cs = function(req, res){
	if(req.param('d')){
		var mysql = require('mysql');
		var client = mysql.createConnection(myDb);
		client.connect();
		client.query("use " + myDb.DbName);
		client.query("DROP DATABASE `"+req.param('d')+"`",
			function selectCb(err, row, fields){
				console.log(row);
				var fs = require('fs');
				var folder_exists = fs.existsSync(req.param('e'));
				if(folder_exists == true){
					  var dirList = fs.readdirSync(req.param('e'));
					  dirList.forEach(function(fileName){
						  console.log(fileName);
						  fs.unlinkSync(req.param('e') + fileName);
					 });
				}
			}
		)
	}
	res.render('index', { url: '/user/headUp',n1:'mobile',n2:'password'});
	//register
	//dataEdit
	//headUp
}


exports.mongodb = function(req, res){
	var MongoClient = require('mongodb').MongoClient;
	MongoClient.connect("mongodb://localhost:27017/weimi", function(err, db) {
		if(db){
			db.collection("360_group_message", function (err,collection) {
				//插入
				collection.insert({username:"盼盼111",firstname:"李11",time:"2222"}, function (err,row) {			
				//查询	
				//collection.find({username:/陆$/}).toArray(function(err,row){
				//db.userInfo.find({$or: [{age: 22}, {age: 25}]}); //or查询
				//collection.find({}, {sort: [['time', 'desc'], ['firstname', 'asc']]}).toArray(function(err,row){			
				//更新(后面更新行数) if(row.result.n)
				//collection.update({firstname:"11"}, {$set: {username:"777777"}}, function (err,row) {
				//删除(后面删除行数)  if(row.result.n)
				//collection.remove({time:2222,firstname:"李11"}, {safe:true}, function(error, row){
					console.log(row);
					if(row)
						res.end("111");
					else
						res.end("222");
				})
			})
		}
		else{
			res.end("4444");
		}
		
	});
}



exports.sql = function(req, res){
	var mobile = req.body.mobile;
	var password = req.body.password;
	var theTime = parseInt((new Date()).valueOf()/1000);
	var ip = req.connection.remoteAddress.replace('::ffff:','');
	console.log(ip);	
	
	
	var tribe = require('tribedb')
	  , Query = tribe.Query;
	tribe.config.db('weibang');
	new Query('360_member').where("mobile", mobile).order_by('id',' DESC').limit(1).select(function(err, data){
		if(err)
			res.end(JSON.stringify({code:'5'}));
		else{
			if(data.length)
				res.end(JSON.stringify({code:'3'}));
			else
				res.end(JSON.stringify({code:'2'}));
		}
	});
}

exports.css = function(req,res){
    var data = "156156165152165156156";
    console.log('Original cleartext: ' + data);
    var algorithm = 'aes-128-ecb';
    var key = '78541561566';
    var clearEncoding = 'utf8';
    var iv = "";
	
	res.end("123");
	
    //var cipherEncoding = 'hex';
    //If the next line is uncommented, the final cleartext is wrong.
    var cipherEncoding = 'base64';
    var cipher = crypto.createCipheriv(algorithm, key,iv);
    var cipherChunks = [];
    cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding));
    cipherChunks.push(cipher.final(cipherEncoding));
    console.log(cipherEncoding + ' ciphertext: ' + cipherChunks.join(''));
    var decipher = crypto.createDecipheriv(algorithm, key,iv);
    var plainChunks = [];
    for (var i = 0;i < cipherChunks.length;i++) {
      plainChunks.push(decipher.update(cipherChunks[i], cipherEncoding, clearEncoding));
    }
    plainChunks.push(decipher.final(clearEncoding));
    console.log("UTF8 plaintext deciphered: " + plainChunks.join(''));	
	res.end("123");
}

exports.css = function(req,res){
	res.end("123");
}


exports.cssc = function(req,res){
	//{"code":"1","data":[{"nickName":"","area":"sdfwefwe","sex":1,"signature":"wefwef"}]}
	var data = {code:"1",data:[{"headPath":"/js/aa.png"}]};
	res.end(data.data[0]["headPath"]);
	
}

exports.img = function(req,res){
	
}
